/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IFSv2.Util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author Fulbert
 */
public class utilCryptUtility {
    
    public static final String AES = "AES";

    public static String encrypt(String value, File keyFile) throws GeneralSecurityException, IOException {
        
        if (!keyFile.exists()) {
            KeyGenerator keyGen = KeyGenerator.getInstance(utilCryptUtility.AES);
            keyGen.init(128);
            SecretKey sk = keyGen.generateKey();
        
            try (FileWriter fw = new FileWriter(keyFile)) {
                fw.write(byteArrayToHexString(sk.getEncoded()));
                fw.flush();
            }
        }
    
        SecretKeySpec sks = getSecretKeySpec(keyFile);
        Cipher cipher = Cipher.getInstance(utilCryptUtility.AES);
        cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
        byte[] encrypted = cipher.doFinal(value.getBytes());
   
        return byteArrayToHexString(encrypted);
    }

    public static String decrypt(String message, File keyFile) throws GeneralSecurityException, IOException {
   
        SecretKeySpec sks = getSecretKeySpec(keyFile);
        Cipher cipher = Cipher.getInstance(utilCryptUtility.AES);
        cipher.init(Cipher.DECRYPT_MODE, sks);
        byte[] decrypted = cipher.doFinal(hexStringToByteArray(message));
      
        return new String(decrypted);
    }

    private static SecretKeySpec getSecretKeySpec(File keyFile) throws NoSuchAlgorithmException, IOException {
    
        byte [] key = readKeyFile(keyFile);
        SecretKeySpec sks = new SecretKeySpec(key, utilCryptUtility.AES);
    
        return sks;
    }

    private static byte [] readKeyFile(File keyFile) throws FileNotFoundException {
        
        String keyValue;
      
        try (Scanner scanner = new Scanner(keyFile).useDelimiter("\\Z")) {
            keyValue = scanner.next();
        }
    
        return hexStringToByteArray(keyValue);
    }

    private static String byteArrayToHexString(byte[] byteVal){
    
        StringBuilder sb = new StringBuilder(byteVal.length * 2);
    
        for (int i = 0; i < byteVal.length; i++) {
            
            int val = byteVal[i] & 0xff;

            if (val < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(val));
        }
    
        return sb.toString().toUpperCase();
    }

    private static byte[] hexStringToByteArray(String str) {
   
        byte[] byteVal = new byte[str.length() / 2];
    
        for (int i = 0; i < byteVal.length; i++) {
      
            int index = i * 2;
      
            int val = Integer.parseInt(str.substring(index, index + 2), 16);
     
            byteVal[i] = (byte)val;
    
        }
    
        return byteVal;
    }

}
